package com.zxy.supplier_system.server.xinyuan.service

import com.zxy.supplier_system.server.utils.IntIdAndName
import com.zxy.supplier_system.server.utils.orElse404
import com.zxy.supplier_system.server.xinyuan.controller.XinyuanGoodsBrandController
import com.zxy.supplier_system.server.xinyuan.entity.XinyuanGoodsBrand
import com.zxy.supplier_system.server.xinyuan.repository.XinyuanGoodsBrandRepository
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class XinyuanGoodsBrandService(
    private val xinyuanGoodsBrandRepository: XinyuanGoodsBrandRepository
) {
    fun findAll(): List<IntIdAndName> {
        return xinyuanGoodsBrandRepository.findAll().map { IntIdAndName(it.id,it.name) }

    }

    @Transactional
    fun createGoodsBrand(request: XinyuanGoodsBrandController.UpdateGoodsBrandRequest) {
        xinyuanGoodsBrandRepository.save(XinyuanGoodsBrand().apply {
            this.name = request.name
        })
    }

    @Transactional
    fun updateGoodsBrand(id: Int, request: XinyuanGoodsBrandController.UpdateGoodsBrandRequest) {
        val goodsBrand = this.xinyuanGoodsBrandRepository.findByIdOrNull(id).orElse404()
        goodsBrand.name = request.name
        this.xinyuanGoodsBrandRepository.findByIdOrNull(id)
    }

    @Transactional
    fun delete(id: Int) {
        this.xinyuanGoodsBrandRepository.deleteById(id)
    }

}
